package com.jgp.security.component;

import com.jgp.config.CacheConfiguration;
import com.jgp.security.props.SecurityConfigPropBean;
import com.jgp.sys.sms.SmsData;
import com.jgp.sys.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-06-02
 */
@Slf4j
@Component
public class TelCodeUtil {
    
    private final String TEL_CODE = CacheConfiguration.TEL_CODE;
    
    private final String CHECK_TEL_CODE_CAN_RESEND = CacheConfiguration.CHECK_TEL_CODE_CAN_RESEND;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private SecurityConfigPropBean securityConfigPropBean;
    
    public Boolean canResend(String tel){
        String switchFlag = redisUtil.get(CHECK_TEL_CODE_CAN_RESEND+":"+tel);
        boolean flag = false;
        if(Objects.isNull(switchFlag)){
            redisUtil.set(CHECK_TEL_CODE_CAN_RESEND+":"+tel,"ok");
            flag = true;
        }
        return flag;
    }
    
    public String send(String tel){
        if(canResend(tel)){
            int index = 0;
            //String code = JGPUtil.random(6);
            String code = "123456";
            redisUtil.set(CHECK_TEL_CODE_CAN_RESEND+":"+tel,"ok");
            String oldCode = redisUtil.get(TEL_CODE+":"+tel);
            if(StringUtils.isNotBlank(oldCode)){
                index = Integer.parseInt(oldCode.split(":")[1]);
            }
            index += 1;
            redisUtil.set(TEL_CODE+":"+tel,code+":"+index);
            SmsData data = new SmsData(tel, securityConfigPropBean.getSmsValidTpl());
            data.addData("code",code);
            data.addData("index",index+"");
            //SmsUtil.send(data);
            if(securityConfigPropBean.getShowSmsCode()){
                log.info("短信验证码["+index+"]:"+code);
            }
            return index+"";
        }
        return null;
    }
    
    public String get(String tel){
        String code = redisUtil.get(TEL_CODE+":"+tel);
        return StringUtils.isNotBlank(code)?code.split(":")[0]:null;
    }
    
    public void reset(String tel){
        String value = redisUtil.get(TEL_CODE+":"+tel);
        redisUtil.set(TEL_CODE+":"+tel,value);
    }
    
    public void delete(String tel){
        redisUtil.delete(TEL_CODE+":"+tel);
        redisUtil.delete(CHECK_TEL_CODE_CAN_RESEND+":"+tel);
    }
    
}
